package com.study.ws.config.ws;

import com.study.ws.config.ws.handler.TextMessageHandler;
import com.study.ws.config.ws.interceptor.AuthHandshakeInterceptor;
import jakarta.websocket.ContainerProvider;
import jakarta.websocket.WebSocketContainer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import java.time.Duration;

/**
 * spring boot 封装的一种处理 ws 协议消息的方式比较 high
 *
 * @author xl-9527
 * @since 2025/3/23
 **/
@EnableWebSocket
@Configuration(proxyBeanMethods = false)
public class WsSocketHandlerConfiguration implements WebSocketConfigurer {

    private final TextMessageHandler lowWsHandler;

    public WsSocketHandlerConfiguration(final TextMessageHandler lowWsHandler) {
        this.lowWsHandler = lowWsHandler;
    }

    @Override
    public void registerWebSocketHandlers(final WebSocketHandlerRegistry registry) {
        registry.addHandler(lowWsHandler, "/ws/text-handler/{userId}")
                .addInterceptors(new AuthHandshakeInterceptor());
//                .addInterceptors(new HttpSessionHandshakeInterceptor());
        // .withSockJS(); 默认 ws 协议在 postman 不可以正常连接使用 withJS 的时候
    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Bean
    public WebSocketContainer wsContainerProvider() {
        final WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer();
        webSocketContainer.setDefaultMaxSessionIdleTimeout(
                Duration.ofSeconds(60).toMillis()
        );
        return webSocketContainer;
    }
}
